$(document).ready(
    function(){
        
        var UI = {};
        (function (UI) {
            
            UI.start = function(){
                /*$.when(Actions.GetUserList({action : "test"})).then(
                    function(data){
                        var html = "";
                        var row = null;
                        for(var i = 0; i<data.length; i++){
                            row = data[i];
                            var accountName = "Unknown";
                            if(row.account_type === "0"){
                                accountName = "Private";
                            } else if(row.account_type === "1"){
                                accountName = "Business";
                            }
                            html += "<tr id='row-" + (i + 1) + "'>";
                            html += "<td id='username-"+(i+1)+"'>" + row.username + "</td>";
                            html += "<td id='email-"+(i+1)+"'>" + row.email + "</td>";
                            html += "<td id='firstname-"+(i+1)+"'>" + row.first_name + "</td>";
                            html += "<td id='lastname-"+(i+1)+"'>" + row.last_name + "</td>";
                            html += "<td id='password-"+(i+1)+"'>" + row.password + "</td>";
                            html += "<td id='accounttype-"+(i+1)+"'>" + accountName + "</td>";
                            html += "</tr>";
                        }
                        $("#new-user-grid").append(html);
                    }
                );*/
            };
            
        }(UI));
        var Helpers = {};
        (function (Helpers) {
            
            
        }(Helpers));
        
        var Actions = {};
        (function (Actions) {
            
            Actions.signUp = function(args) {
                console.log("%c runSQL signUp", "color: green");
                var dfd = new $.Deferred();
                $.ajax({
                    type: "POST",
                    url: "../resources/helpers/signUpDb.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        console.log("%c Returned from signUp:","color: green");
                        console.log(data);
                        data = JSON.parse(data);
                        dfd.resolve(data);
                        dfd.resolve();
                    }
                });
                return dfd.promise();
            };
            
            Actions.checkEmail = function(args) {
                console.log("%c runSQL checkEmail", "color: green");
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/checkEmail.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        console.log("%c Returned from checkEmail:","color: green");
                        console.log(data);
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.checkUsername = function(args) {
                console.log("%c runSQL checkUsername", "color: green");
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/checkUsername.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        console.log("%c Returned from checkUsername:","color: green");
                        console.log(data);
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
        }(Actions));
        
        var Controller = {};
        (function (Controller) {
            
            function checkEmail(){
                var isEmailValid = validateEmail($("#signup-email").val());
                var isPasswordValid = validatePassword($("#signup-password").val());
                var isPassword2Valid = validatePassword2($("#signup-password").val(), $("#signup-password2").val());
                var isUserNameValid = validateUsername($("#signup-username").val());
                if(isEmailValid === -1){ //email is empty
                    $("#signup-email-error").removeClass("hidden");
                    $("#signup-email-check").addClass("hidden");
                    $("#signup-email-msg").text("Vennligst oppgi en e-post adresse.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }
                if(isEmailValid === -2){ //email is not valid
                    $("#signup-email-error").removeClass("hidden");
                    $("#signup-email-check").addClass("hidden");
                    $("#signup-email-msg").text("Vennligst oppgi en gyldig e-post adresse.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                $("#signup-email-error").addClass("hidden");
                $("#signup-email-check").removeClass("hidden");
                $("#signup-email-msg").text("");

                if(isPasswordValid < 0 || isPassword2Valid < 0 || isUserNameValid < 0 || !$("#signup-firstname").val() || !$("#signup-lastname").val() || !$("#signup-agreement:checked").val()){ //password is empty or not valid
                    $("#signUpBtn").addClass("disabled");
                } else{
                    $("#signUpBtn").removeClass("disabled");
                }
            }
            
            function checkPassword(){
                var isPasswordValid = validatePassword($("#signup-password").val());
                var isPassword2Valid = validatePassword2($("#signup-password").val(), $("#signup-password2").val());
                var isEmailValid = validateEmail($("#signup-email").val());
                var isUsernameValid = validateUsername($("#signup-username").val());
                if(isPasswordValid === -1){ //password is empty
                    $("#signup-pw-error").removeClass("hidden");
                    $("#signup-pw-check").addClass("hidden");
                    $("#signup-pw-msg").text("Vennligst oppgi et passord.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                if(isPasswordValid === -2){ //password is shorter than 8 characters
                    $("#signup-pw-error").removeClass("hidden");
                    $("#signup-pw-check").addClass("hidden");
                    $("#signup-pw-msg").text("Passordet må bestå av minst 8 tegn.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                $("#signup-pw-error").addClass("hidden");
                $("#signup-pw-check").removeClass("hidden");
                $("#signup-pw-msg").text("");

                if(isPassword2Valid < 0 || isEmailValid < 0 || isUsernameValid < 0 || !$("#signup-firstname").val() || !$("#signup-lastname").val() || !$("#signup-agreement:checked").val()){ //email is empty or not valid
                    $("#signUpBtn").addClass("disabled");
                } else{
                    $("#signUpBtn").removeClass("disabled");
                }
            }
            
            function checkPassword2(){
                var isPasswordValid = validatePassword($("#signup-password").val());
                var isPassword2Valid = validatePassword2($("#signup-password").val(), $("#signup-password2").val());
                var isEmailValid = validateEmail($("#signup-email").val());
                var isUsernameValid = validateUsername($("#signup-username").val());
                if(isPassword2Valid === -1){ //password2 is empty
                    $("#signup-pw2-error").removeClass("hidden");
                    $("#signup-pw2-check").addClass("hidden");
                    $("#signup-pw2-msg").text("Vennligst gjenta passordet.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                if(isPassword2Valid === -2){ //password2 does not match password
                    $("#signup-pw2-error").removeClass("hidden");
                    $("#signup-pw2-check").addClass("hidden");
                    $("#signup-pw2-msg").text("Passordene er ulike.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                $("#signup-pw2-error").addClass("hidden");
                $("#signup-pw2-check").removeClass("hidden");
                $("#signup-pw2-msg").text("");

                if(isPasswordValid < 0 || isEmailValid < 0 || isUsernameValid < 0 || !$("#signup-firstname").val() || !$("#signup-lastname").val() || !$("#signup-agreement:checked").val()){ //email is empty or not valid
                    $("#signUpBtn").addClass("disabled");
                } else{
                    $("#signUpBtn").removeClass("disabled");
                }
            }
            
            function checkUsername(){
                var isPasswordValid = validatePassword($("#signup-password").val());
                var isPassword2Valid = validatePassword2($("#signup-password").val(), $("#signup-password2").val());
                var isEmailValid = validateEmail($("#signup-email").val());
                var isUsernameValid = validateUsername($("#signup-username").val());
                if(isUsernameValid === -1){ //password is empty
                    $("#signup-username-error").removeClass("hidden");
                    $("#signup-username-check").addClass("hidden");
                    $("#signup-username-msg").text("Vennligst oppgi et brukernavn.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                if(isUsernameValid === -2){ //password is shorter than 8 characters
                    $("#signup-username-error").removeClass("hidden");
                    $("#signup-username-check").addClass("hidden");
                    $("#signup-username-msg").text("Brukernavnet må bestå av minst 6 tegn.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                $("#signup-username-error").addClass("hidden");
                $("#signup-username-check").removeClass("hidden");
                $("#signup-username-msg").text("");

                if(isEmailValid < 0 || isPasswordValid < 0 || isPassword2Valid < 0 || !$("#signup-firstname").val() || !$("#signup-lastname").val() || !$("#signup-agreement:checked").val()){ //email is empty or not valid
                    $("#signUpBtn").addClass("disabled");
                } else{
                    $("#signUpBtn").removeClass("disabled");
                }
            }
            
            function checkFirstname(){
                var isPasswordValid = validatePassword($("#signup-password").val());
                var isPassword2Valid = validatePassword2($("#signup-password").val(), $("#signup-password2").val());
                var isEmailValid = validateEmail($("#signup-email").val());
                var isUsernameValid = validateUsername($("#signup-username").val());
                
                if(!$("#signup-firstname").val()){ //password is empty
                    $("#signup-firstname-error").removeClass("hidden");
                    $("#signup-firstname-check").addClass("hidden");
                    $("#signup-firstname-msg").text("Vennligst oppgi ditt fornavn.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }

                $("#signup-firstname-error").addClass("hidden");
                $("#signup-firstname-check").removeClass("hidden");
                $("#signup-firstname-msg").text("");

                if(isEmailValid < 0 || isPasswordValid < 0 || isPassword2Valid < 0 || isUsernameValid < 0 || !$("#signup-lastname").val() || !$("#signup-agreement:checked").val()){ //email is empty or not valid
                    $("#signUpBtn").addClass("disabled");
                } else{
                    $("#signUpBtn").removeClass("disabled");
                }
            }
            
            function checkLastname(){
                var isPasswordValid = validatePassword($("#signup-password").val());
                var isPassword2Valid = validatePassword2($("#signup-password").val(), $("#signup-password2").val());
                var isEmailValid = validateEmail($("#signup-email").val());
                var isUsernameValid = validateUsername($("#signup-username").val());
                
                if(!$("#signup-lastname").val()){ //password is empty
                    $("#signup-lastname-error").removeClass("hidden");
                    $("#signup-lastname-check").addClass("hidden");
                    $("#signup-lastname-msg").text("Vennligst oppgi ditt etternavn.");
                    $("#signUpBtn").addClass("disabled");
                    return;
                }
                
                $("#signup-lastname-error").addClass("hidden");
                $("#signup-lastname-check").removeClass("hidden");
                $("#signup-lastname-msg").text("");

                if(isEmailValid < 0 || isPasswordValid < 0 || isPassword2Valid < 0 || isUsernameValid < 0 || !$("#signup-firstname").val() || !$("#signup-agreement:checked").val()){ //email is empty or not valid
                    $("#signUpBtn").addClass("disabled");
                } else{
                    $("#signUpBtn").removeClass("disabled");
                }
            }
            
            function checkAgreement(){
                var isPasswordValid = validatePassword($("#signup-password").val());
                var isPassword2Valid = validatePassword2($("#signup-password").val(), $("#signup-password2").val());
                var isEmailValid = validateEmail($("#signup-email").val());
                var isUsernameValid = validateUsername($("#signup-username").val());

                if(isEmailValid < 0 || isPasswordValid < 0 || isPassword2Valid < 0 || isUsernameValid < 0 || !$("#signup-firstname").val() || !$("#signup-agreement:checked").val()){ //email is empty or not valid
                    $("#signUpBtn").addClass("disabled");
                } else{
                    $("#signUpBtn").removeClass("disabled");
                }
            }
            
            function signUpClicked(){
                var args2 = {
                    action: "select",
                    username: $("#signup-username").val(),
                    email: $("#signup-email").val()
                };
                $.when(Actions.checkUsername(args2), Actions.checkEmail(args2)).then(
                    function(usernameItems, emailItems){
                        if(usernameItems.username || emailItems.email){
                            if(usernameItems.username){
                                $("#signup-username-error").removeClass("hidden");
                                $("#signup-username-check").addClass("hidden");
                                $("#signup-username-msg").text("Brukernavnet er allerede registrert.");
                                $("#signUpBtn").addClass("disabled");
                            }
                            if(emailItems.email){
                                $("#signup-email-error").removeClass("hidden");
                                $("#signup-email-check").addClass("hidden");
                                $("#signup-email-msg").text("Denne e-post adressen er allerede registrert.");
                                $("#signUpBtn").addClass("disabled");
                            }
                        } else{
                            var args = {
                                firstname : $("#signup-firstname").val(),
                                lastname : $("#signup-lastname").val(),
                                email : $("#signup-email").val(),
                                username: $("#signup-username").val(),
                                password : $("#signup-password").val()
                            };
                            $.when(Actions.signUp(args)).then(
                                function(returnItems){
                                    if(returnItems){
                                        $("#signup-feedback").text("En verifiserings e-post har blitt sendt til " + $("#signup-email").val() + ". Vennligst gå inn på denne lenken for å verifisere registreringen.");
                                    }
                                }
                            );
                        }
                    }
                );
            }
            
            $("#signup-email").unbind("input propertychange change keyup").bind("input propertychange keyup", function() {
                checkEmail();
            });
            
            $("#signup-password").unbind("input propertychange change keyup change").bind("input propertychange keyup change", function() {
                checkPassword();
            });
            
            $("#signup-password2").unbind("input propertychange change keyup change").bind("input propertychange keyup change", function() {
                checkPassword2($("#signup-password").val(), $("#signup-password2").val());
            });
            
            $("#signup-username").unbind("input propertychange change keyup change").bind("input propertychange keyup change", function() {
                checkUsername();
            });
            
            $("#signup-firstname").unbind("input propertychange change keyup change").bind("input propertychange keyup change", function() {
                checkFirstname();
            });
            
            $("#signup-lastname").unbind("input propertychange change keyup change").bind("input propertychange keyup change", function() {
                checkLastname();
            });
            
            $("#signup-agreement").unbind("click change").bind("click change", function() {
                checkAgreement();
            });
            
            Controller.init= function(){
                $("#signUpBtn").unbind("click").bind("click", signUpClicked);
            };
            
        }(Controller));	
        
        UI.start();
        Controller.init();
    }
);